<template>
  <div class="flex-shrink-0 h-auto">
    hello
    <!-- 推荐问题 -->
    <div class="recommend-question" v-if="!loading && recommendQuestions.length">
      <span class="text-sm text-text-03 black:text-text-03-dark">猜你想问：</span>
      <div class="flex flex-wrap mt-[6px] justify-start gap-2 items-center">
        <span
          class="px-2 py-[6px] rounded border-border-02 black:border-border-02-dark border max-w-full bg-background-01 black:bg-background-01-dark text-sm text-text-04 black:text-text-04 flex justify-start items-center gap-2 cursor-pointer hover:border-border-04 black:hover:border-border-04-dark hover:bg-aif10enterbg"
          v-for="(item, index) in recommendQuestions"
          :key="index"
          @click="sendMessage(item)"
          v-track:click="{
            id: 'thspc_f10_copilot_chatpanel_recomed',
            logmap: () => ({ content: item })
          }"
        >
          <el-icon><QuestionEnter /></el-icon>
          <div class="truncate">{{ item }}</div>
        </span>
      </div>
    </div>

    <!-- 问句输入框/指令等 -->
    <div
      ref="questionBox"
      class="bg-white black:bg-black rounded-md py-2 px-3 mt-2 border border-border-02 black:border-border-02-dark"
      :class="{ 'border-gradient': questionBoxActive }"
      @click="activeAskBox"
    >
      <!-- 选择的内容 -->
      <div
        v-if="showSelectContent"
        class="pb-2 border-b-[1px] mb-3 border-b-border-03 black:border-b-border-03-dark"
      >
        <div
          class="copy-content text-xs bg-background-03 black:bg-background-03-dark px-2 py-1 rounded relative"
        >
          <span class="flex items-center justify-start gap-[6px]">
            <el-icon class="!text-text-01 black:!text-text-01-dark">
              <SelectSection v-if="selectType === 'SECTION'" />
              <SelectContent v-else />
            </el-icon>
            {{ SELECTTYPE[selectType!] }}
          </span>
          <p class="text-text-03 mt-1 line-clamp-2">“{{ selectContent }}”</p>
          <el-icon
            class="!absolute -right-1 -top-1 cursor-pointer"
            @click.stop="resetAskBoxStatus"
            :size="16"
          >
            <CloseQuote />
          </el-icon>
        </div>
        <!-- 命令行工具 -->
        <div class="tools flex justify-end items-center gap-2 mt-2">
          <span
            class="text-sm h-6 px-2 bg-background-03 black:bg-background-03-dark rounded text-text-04 black:text-text-04-dark flex justify-center items-center cursor-pointer hover:bg-aif10enterbg"
            v-for="item in chatCommands"
            :key="item.id"
            @click="commondClick(item)"
            v-track:click="{
              id: 'thspc_f10_copilot_chatpanel_command',
              logmap: () => ({ type: item.id, content: item.name })
            }"
          >
            {{ item.name }}
          </span>
        </div>
      </div>
      <!-- 真实输入框 -->
      <textarea
        class="w-full h-[54px] focus:outline-none resize-none text-sm !caret-text-04 black:!caret-text-04-dark bg-white black:bg-black"
        v-model="question"
        :placeholder="placeholder"
        ref="questionInput"
        @keyup.enter.prevent="sendMessage()"
        v-track:input="{
          id: 'thspc_f10_copilot_chatpanel_ask',
          action: 'click',
          logmap: () => ({ content: question, from_object: selectContent })
        }"
      ></textarea>
      <div class="flex justify-between items-center">
        <el-tooltip effect="customized" placement="top" content="清除上下文">
          <el-icon class="cursor-pointer !w-[20px] !h-[20px]r" @click="resetChatSession()"
            ><ChatReset
              class="!w-[20px] !h-[20px] hover:text-text-04 black:hover:text-text-04-dark"
          /></el-icon>
        </el-tooltip>

        <el-icon
          class="cursor-pointer"
          :class="{ 'opacity-60': !question, '!cursor-not-allowed': !question || loading }"
          @click="sendMessage()"
          v-track:click="{
            id: 'thspc_f10_copilot_chatpanel_ask',
            logmap: () => ({ content: question, from_object: selectContent })
          }"
          ><SendMessage
        /></el-icon>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { computed, ref, type Ref } from 'vue'
import {
  QuestionEnter,
  SelectContent,
  SendMessage,
  CloseQuote,
  SelectSection,
  ChatReset
} from '@/components/icons'
import { onClickOutside } from '@vueuse/core'
import {
  ChatMessages,
  Message,
  type QueryMessage,
  type RefrenceResource
} from '@/common/models/chat-message'
import { useSessionStore } from '@/stores/session'
import { usePanelStore } from '@/stores/panel'
import { getEventBus } from '@/common/services/chat-event-bus'
import { SELECTTYPE } from '@/common/config/const'
import { getRecommendQuestion } from '../../services/chat-api'
import type { ChartSelectContent } from '@/common/models/aigc-data-vis'

const props = defineProps<{
  loading: boolean
}>()

const {
  messageEventBus,
  sectionSelectEventBus,
  sectionOperatorEventBus,
  pageChangeEventBus,
  questionUpdateEventBus,
  chatResetEventBus,
  robotMessageEventBus
} = getEventBus()

// 问句
const question = ref('')
// 输入框Dom元素
const questionBox = ref()
// 输入框是否激活状态
const questionBoxActive = ref(false)
// 文本框的placeholder
const placeholder = ref('')
// 文本框Dom元素
const questionInput = ref()
// 命令列表 mock
const chatCommands: Ref<{ id: string; name: string }[]> = ref([])
// 推荐问题 mock
const recommendQuestions: Ref<string[]> = ref([])

// 选择的内容 mock
const selectContent: Ref<null | string> = ref(null)
// 是否显示选择的内容
const showSelectContent = ref(false)
// 选择的类型
const selectType: Ref<string | null> = ref(null)
// 选择的数据
const selectData: Ref<ChartSelectContent | null> = ref(null)
// 命令id
const commondId: Ref<string | null> = ref(null)

// 页面会话session
const sessionStore = useSessionStore()

const panelStore = usePanelStore()

const loginStatusInJS = computed(() => window.loginIssue.isLogin())

// 交互：点击外部输入框样式重置
onClickOutside(questionBox, () => (questionBoxActive.value = false))

// 交互：发送问句消息
function sendMessage(item?: string) {
  const session_id = sessionStore.session?.session_id || 'mock_session_id'

  const query = item || question.value.replace(/\n/g, '')
  question.value = query

  if (!query || props.loading) return
  const queryMessage: QueryMessage = {
    action: 'CREATE',
    query,
    session_id,
    engine: 'default',
    command_id: commondId.value
  }
  if (showSelectContent.value) {
    queryMessage.ref = formatRefParam()
  }
  const message = new Message(session_id, 'USER', queryMessage)
  const chatMessage = new ChatMessages('USER', [message])
  questionInput.value.focus()
  messageEventBus.emit(chatMessage)
}

// 设置引用内容请求参数
function formatRefParam(): RefrenceResource {
  const section = panelStore.selectSection
  const panel = panelStore.currentPanel
  return {
    type:
      (selectType.value && (selectType?.value.includes('INDEX') ? 'INDEX' : 'SECTION')) || 'PANEL',
    select_title: selectType.value || null,
    select_content: selectContent.value || null,
    data: selectData.value?.data || null,
    section_name: section?.title || null,
    sid: section?.id || null,
    pid: panel?.id || null,
    panel_name: panel?.title || null
  }
}

// 对外：状态重置
function resetAskBoxStatus() {
  question.value = ''
  questionBoxActive.value = false
  placeholder.value = '询问有关的问题...'
  chatCommands.value = []
  selectContent.value = null
  showSelectContent.value = false
  selectType.value = null
  selectData.value = null
  panelStore.setSelectSection(null)
  commondId.value = null
}

function resetQuestion() {
  recommendQuestions.value = []
  panelStore.setRecommendQuestions([])
}

// 根据当前条件获取推荐问题
async function setQuestion() {
  resetQuestion()
  const params = formatRefParam()
  const res = await getRecommendQuestion(params)
  const questions = res.questions.sort((pre, next) => pre.length - next.length).slice(0, 2)
  recommendQuestions.value = questions
  panelStore.setRecommendQuestions(questions)
}

// 监听：问答消息中的推荐问句
questionUpdateEventBus.on(({ questions }) => {
  recommendQuestions.value = questions.sort((pre, next) => pre.length - next.length).slice(0, 2)
  panelStore.setRecommendQuestions(questions)
  robotMessageEventBus.emit({
    type: 'question',
    width: '320px',
    flush: true,
    content: { data: recommendQuestions.value }
  })
})

// 监听：模块选中
sectionSelectEventBus.on(({ section, data, commands }) => {
  if (!loginStatusInJS.value) {
    return
  }

  placeholder.value = '询问有关的问题...'
  activeAskBox()

  // 点击表格内容
  if (data) {
    selectContent.value = data.selectedValue
    selectData.value = data
    selectType.value = data.data.length > 1 ? 'INDEX_ROW_COL' : 'INDEX_OBJ'
  } else {
    selectType.value = 'SECTION'
    selectContent.value = section.title
    selectData.value = null
  }
  chatCommands.value = commands

  robotMessageEventBus.emit({
    type: 'contentSelect',
    width: '320px',
    flush: panelStore.selectSection?.id !== section.id,
    content: {
      selectContent: selectContent.value,
      selectData: selectData.value,
      selectType: selectType.value,
      chatCommands: chatCommands.value
    }
  })

  // 选择的内容发生变化，重新获取推荐问题
  if (!panelStore.selectSection) {
    resetQuestion()
    panelStore.setSelectSection(section)
  }
  if (section.id !== panelStore.selectSection?.id || !recommendQuestions.value.length) {
    panelStore.setSelectSection(section)
    setQuestion()
  }

  panelStore.setSelectSection(section)
  showSelectContent.value = true
})

// 监听：页面切换
pageChangeEventBus.on(async ({ first }) => {
  resetAskBoxStatus()
  resetQuestion()
  await setQuestion()
  if (first) return
  console.log('wj',recommendQuestions.value);
  
  robotMessageEventBus.emit({
    type: 'question',
    width: '320px',
    flush: true,
    content: { data: recommendQuestions.value }
  })
})

function activeAskBox() {
  questionInput.value.focus()
  questionBoxActive.value = true
}

// 监听：指令点击
function commondClick(command: { id: string; name: string }) {
  commondId.value = command.id
  // 需输入内容再走模型
  if (command.id === 'card_edit') {
    placeholder.value = `将“${panelStore.selectSection?.value}”修改为：`
  }
  if (command.id === 'visual_insight') {
    placeholder.value = `输入洞察要素，如：最大值、平均值等`
  }

  // 直接走模型
  if (
    [
      'index_explain',
      'index_graphic',
      'card_analyze',
      'card_graphic',
      'card_explain',
      'dynamic_command_index_expand',
      'dynamic_command_index_abbreviation'
    ].includes(command.id)
  ) {
    question.value = command.name
    sendMessage()
  }

  // 本地处理
  if (['card_change', 'close_insight'].includes(command.id)) {
    sectionOperatorEventBus.emit({ id: command.id, section: panelStore.selectSection })
    commondId.value = null
  }
  if (['card_delete'].includes(command.id)) {
    sectionOperatorEventBus.emit({ id: 'card_delete', section: panelStore.selectSection })
    resetAskBoxStatus()
    resetQuestion()
    robotMessageEventBus.emit(null)
  }
}

function resetChatSession() {
  if (props.loading) return
  chatResetEventBus.emit()
}

defineExpose({
  resetAskBoxStatus,
  resetQuestion,
  sendMessage,
  commondClick
})
</script>
